package com.asen.test.view


import android.view.View
import android.widget.ImageView
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.asen.app.router.ActivityPath
import com.asen.libcommon.base.BaseListActivity
import com.asen.libcommon.base.BaseListAdapter
import com.asen.libcommon.base.extend.extRefreshFinish
import com.asen.libcommon.base.extend.extAddDispose
import com.asen.libcommon.base.extend.extImmersionBar
import com.asen.libcommon.http.*
import com.asen.libcommon.http.interceptor.LoggerInterceptor
import com.asen.libcommon.http.livedata.LiveDataCallAdapterFactory
import com.asen.libcommon.util.GsonUtil
import com.asen.test.R
import com.asen.test.http.AppApi
import com.asen.test.http.AppRetrofit
import com.asen.test.bean.NewsBean
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.scwang.smart.refresh.layout.api.RefreshLayout
import okhttp3.MediaType
import okhttp3.OkHttpClient
import okhttp3.RequestBody
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.moshi.MoshiConverterFactory
import java.lang.Exception


/**
 * @author : asenLiang
 * @date   : 2020/12/10
 * @e-mail : liangAisiSen@163.com
 * @desc   : 新闻列表,分别说明了怎么使用 moshi / RX / liveData 封装网路请求框架
 */
@Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")
@Route(path = ActivityPath.TestModule.NewsActivity)
class NewsActivity(private val mApi: AppApi = AppRetrofit.service!!) : BaseListActivity<NewsBean>() {

    override fun getItemLayoutId() =
        R.layout.adapter_list_item_news

    override suspend fun initView() { super.initView();extImmersionBar(false);autoRefresh() }

    override fun onRefreshUpdate(re: RefreshLayout, isRe: Boolean) {
        // TODO: rx封装请求
        extAddDispose(mApi.getNews().extRxRequest(onSuccess = { addData(it.result) }, onEnd = { re.extRefreshFinish(isRe) }))
        // TODO: 携程封装请求
        lifecycleScope.extMoShiRequest(
            onStart = { lifecycleScope.extLiveDataHttp(mApi.getNewsBean()).observe(this, Observer { addData(it) }) },
            onEnd = { re.extRefreshFinish(isRe) }
        )
        // TODO: LiveData封装
        mApi.getLiveDataNews().extLiveDataRequest(this, onSuccess = { addData(it.result) }, onEnd = { re.extRefreshFinish(isRe) })
        /** 测试itop接口数据:https://devapicard.itop123.com */
        val api: AppApi = getRetrofit().create(AppApi::class.java)
        extAddDispose(api.getTagList().extRxRequest(onSuccess = {}, onEnd = {}))
        lifecycleScope.extMoShiRequest(onStart = { api.getTagListLive() }, onEnd = {})
        api.getLiveDataNews().extLiveDataRequest(this, onSuccess = {}, onEnd = {})
        /** 蒲公英接口 */
        val api1 = getRetrofit1().create(AppApi::class.java)

        try {
            val checkBean = checkBean()
            api1.check(checkBean.extBody()).observe(this, Observer {
                val ss =it
            })
        }catch (err:Exception){
            val ss =err
        }
    }
    /**
     * 将Dto数据转成对象
     */
    private fun checkBean.extBody()= RequestBody.create(MediaType.parse("application/json; charset=utf-8"), GsonUtil.toJson(this))

    data class checkBean(val _api_key:String="a82604548dada127e99c36f26098694b",val appKey:String="84f390352629413a0b861845616b0a7f",val buildVersion:String="")

    // iTop接口
    private fun getRetrofit() = Retrofit.Builder()
        .baseUrl("https://devapicard.itop123.com")
        .addConverterFactory(MoshiConverterFactory.create())
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .addCallAdapterFactory(LiveDataCallAdapterFactory())
        .client(OkHttpClient.Builder().apply { addInterceptor(LoggerInterceptor()) }.build())
        .build()

    // 蒲公英接口
    private fun getRetrofit1() = Retrofit.Builder()
        .baseUrl("https://www.pgyer.com")
        .addConverterFactory(MoshiConverterFactory.create())
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .addCallAdapterFactory(LiveDataCallAdapterFactory())
        .client(OkHttpClient.Builder().apply { addInterceptor(LoggerInterceptor()) }.build())
        .build()

    override fun onItemClick(a: BaseListAdapter<NewsBean>, v: View, position: Int) {}

    override fun convert(vh: BaseViewHolder, t: NewsBean) {
        val image = vh.getView<ImageView>(R.id.iv_pic)
        Glide.with(image).load(t.image)
            .transform(CenterCrop(), RoundedCorners(10)).into(image)
        vh.setText(R.id.tv_title, t.title)
        vh.setText(R.id.tv_time, t.passtime)
    }

}